package org.comparator4j.util;

import java.util.HashSet;
import java.util.Set;

public class SuperClassFinder {
	public static Class<? extends Object> findSuperClass(Object o1, Object o2) {
		if (o1 == null || o2 == null) {
			return null;
		}
		Set<Class<? extends Object>> set =
				new HashSet<Class<? extends Object>>();
		fillClassSet(o1.getClass(), set);

		return findFromClassSet(o2.getClass(), set);
	}

	private static Class<? extends Object> findFromClassSet(
			Class<? extends Object> claz, Set<Class<?>> set) {
		if (claz == Object.class) {
			return Object.class;
		}
		if (set.contains(claz)) {
			return claz;
		}
		return findFromClassSet(claz.getSuperclass(), set);
	}

	private static void fillClassSet(Class<? extends Object> claz,
			Set<Class<? extends Object>> set) {
		set.add(claz);
		if (claz == Object.class) {
			return;
		}
		fillClassSet(claz.getSuperclass(), set);
	}
}
